// app.js
const express = require('express');
const bodyParser = require('body-parser');
const FeiFanService = require('./feifan.service');
const TaskService = require('./task.service');

const app = express();
const port = 3333;

const tokenService = new FeiFanService();
const taskService = new TaskService();

// 解析 application/json
app.use(bodyParser.json());

// 添加或更新 token
app.post('/add-token', async (req, res) => {
    try {
        const param = req.body;
        const result = await tokenService.addOrUpDateToken(param);
        res.json({ message: result });
    } catch (e) {
        res.status(500).json({ error: '更新 token 失败' });
    }
});

//查询 token列表
app.get('/get-token', async (req, res) => {
    try {
        const result = await tokenService.selectAllUserToken();
        res.json({ message: result });
    } catch (e) {
        res.status(500).json({ error: '获取 token 失败' });
    }
});

app.get('/get-detail-by-username', async (req, res) => {
    const { userName } = req.query;
    if (userName) {
        try {
            const result = await tokenService.selectUserTokenByUsername(userName);
            res.json({ message: result });
        } catch (e) {
            res.status(500).json({ error: `获取${userName} token 失败` });
        }
    } else {
        res.status(500).json({ error: '域账号不能为空' });
    }

});

// 删除token
app.get('/delete-token', async (req, res) => {
    const { userName } = req.query;
    if (userName) {
        const isSuccess = await tokenService.deleteToken(userName);
        if (isSuccess) {
            res.json({ message: '删除成功' });
        } else {
            res.status(500).json({ error: '删除失败' });
        }
    } else {
        res.status(500).json({ error: '域账号不能为空' });
    }
});

// 手动触发任务
app.get('/run-job-all', async (req, res) => {
    await tokenService.jobStartAll();
    res.json({ message: '任务执行完成' });
});

// 手动触发任务
app.get('/run-job', async (req, res) => {
    const { userName } = req.query;
    if (userName) {
        try {
            await tokenService.jobStart(userName);
            res.json({ message: '任务执行完成' });
        } catch (e) {
            res.status(500).json({ error: '任务执行失败' });
        }
    } else {
        res.status(500).json({ error: '域账号不能为空' });
    }
});

app.get('/get-objects-by-username', async (req, res) => {
    const { userName } = req.query;
    if (userName) {
        try {
            const detail = await tokenService.selectUserTokenByUsername(userName);
            const result = await tokenService.getObjectsByToken(detail.token);
            res.json({ message: result });
        } catch (e) {
            res.status(500).json({ error: `获取${userName} token 失败` });
        }
    } else {
        res.status(500).json({ error: '域账号不能为空' });
    }
});

/*****************************************************************************************************************************************************
 * 任务相关接口
 ******************************************************************************************************************************************************************************************/
const taskHandler = async (task) => {
    const users = task.userNames.split(',');
    for (const user of users) {
        await tokenService.jobStart(user.trim());
    }
};

/**
 * 根据任务ID执行对应的任务
 * @param {string} taskId - 任务唯一标识
 */
const taskIdHandler = async (taskId) => {
    try {
        // 获取所有任务
        const tasks = await taskService.selectAllTask();

        // 查找指定ID的任务
        const task = tasks.find(t => t.id === taskId);

        if (!task) {
            console.error(`任务未找到，ID: ${taskId}`);
            return;
        }

        if (!task.userNames || task.userNames.trim() === '') {
            console.warn(`任务没有绑定用户，ID: ${taskId}`);
            return;
        }

        // 拆分用户名并依次执行任务
        const users = task.userNames.split(',');
        for (const user of users) {
            const cleanUser = user.trim();
            if (cleanUser) {
                await tokenService.jobStart(cleanUser);
            }
        }

    } catch (error) {
        console.error(`执行任务失败，ID: ${taskId}`, error);
    }
};
// app.js 启动时恢复所有启用的任务
async function initScheduledTasks() {
    await taskService.loadAllTasksAndSchedule(taskHandler);
}

initScheduledTasks().then(() => {
    console.log('定时任务初始化完成');
});

// 查询任务列表
app.get('/get-task-list', async (req, res) => {
    try {
        const result = await taskService.selectAllTask();
        res.json({ message: { list: result, total: result.length } });
    } catch (e) {
        res.status(500).json({ error: '获取 task失败' });
    }
});

app.post('/update-task', async (req, res) => {
    try {
        const param = req.body;
        const result = await taskService.addOrUpDateTask(param, taskHandler);
        res.json({ message: result });
    } catch (e) {
        res.status(500).json({ error: '更新 task失败' });
    }
});

app.get('/delete-task-by-id', async (req, res) => {
    const { id } = req.query;
    if (id) {
        const isSuccess = await taskService.deleteTaskById(id);
        if (isSuccess) {
            res.json({ message: '删除成功' });
        } else {
            res.status(500).json({ error: '删除失败' });
        }
    } else {
        res.status(500).json({ error: 'id不能为空' });
    }
});

app.get('/start-task-by-id', async (req, res) => {
    const { id } = req.query;
    if (id) {
        const isSuccess = await taskService.startTaskById(id, taskHandler);
        if (isSuccess) {
            res.json({ message: '启动成功' });
        } else {
            res.status(500).json({ error: '启动失败' });
        }
    } else {
        res.status(500).json({ error: 'id不能为空' });
    }
});

app.get('/stop-task-by-id', async (req, res) => {
    const { id } = req.query;
    if (id) {
        const isSuccess = await taskService.stopTaskById(id);
        if (isSuccess) {
            res.json({ message: '禁用成功' });
        } else {
            res.status(500).json({ error: '禁用失败' });
        }
    } else {
        res.status(500).json({ error: 'id不能为空' });
    }
});

// 获取任务状态
app.get('/get-task-status', async (req, res) => {
    try {
        const status = taskService.getTaskStatus();
        res.json({ message: status });
    } catch (error) {
        res.status(500).json({ error: '获取任务状态失败' });
    }
});

// 重新加载所有任务
app.get('/reload-tasks', async (req, res) => {
    try {
        await taskService.reloadAllTasks(taskHandler);
        res.json({ message: '任务重新加载成功' });
    } catch (error) {
        res.status(500).json({ error: '重新加载任务失败' });
    }
});


/*****************************************************************************************************************************************************
 * 单个任务拆分接口
 ******************************************************************************************************************************************************************************************/


// 阅读指定文章
app.get('/read-article-by-id', async (req, res) => {
    const { articleId } = req.query;
    if (articleId) {
        try {
            await tokenService.readArticle(articleId);
            res.json({ message: '阅读任务执行完成' });
        } catch (error) {
            res.status(500).json({ error: '阅读任务执行失败' });
        }
    } else {
        res.status(500).json({ error: 'postId不能为空' });
    }
});

// 点赞某篇文章
app.get('/like-article-by-id', async (req, res) => {
    const { articleId } = req.query;
    if (articleId) {
        await tokenService.likeEntity(articleId);
        res.json({ message: '点赞任务执行完成' });
    } else {
        res.status(500).json({ error: 'id不能为空' });
    }
});

// 收藏某篇文章
app.get('/collect-article-by-id', async (req, res) => {
    const { articleId } = req.query;
    if (articleId) {
        const isSuccess = await tokenService.collectEntity(articleId);
        res.json({ message: isSuccess });
    } else {
        res.status(500).json({ error: 'id不能为空' });
    }
});

// 阅读指定文章
app.get('/read-article-by-username', async (req, res) => {
    const { userName, articleId } = req.query;
    if (userName && articleId) {
        try {
            const result = await tokenService.readArticleByUserName(userName, articleId);
            res.json({ message: result });
        } catch (error) {
            res.status(500).json({ error: '阅读任务执行失败' });
        }
    } else {
        res.status(500).json({ error: 'userName和articleId不能为空' });
    }
});

// 点赞指定文章
app.get('/like-article-by-username', async (req, res) => {
    const { userName, articleId } = req.query;
    if (userName && articleId) {
        try {
            const result = await tokenService.likeArticleByUserName(userName, articleId);
            res.json({ message: result });
        } catch (error) {
            res.status(500).json({ error: '点赞任务执行失败' });
        }
    } else {
        res.status(500).json({ error: 'userName和articleId不能为空' });
    }
});

// 收藏指定文章
app.get('/collect-article-by-username', async (req, res) => {
    const { userName, articleId } = req.query;
    if (userName && articleId) {
        try {
            const result = await tokenService.collectArticleByUserName(userName, articleId);
            res.json({ message: result });
        } catch (error) {
            res.status(500).json({ error: '收藏任务执行失败' });
        }
    } else {
        res.status(500).json({ error: 'userName和articleId不能为空' });
    }
});


app.listen(port, () => {
    console.log(`服务运行在 http://localhost:${port}`);
});
